﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Bamboo.CodeCat
{
    /// <summary>
    /// 可并发执行的替换任务
    /// </summary>
    public class ReplaceTask
    {
        /// <summary>
        /// 模板
        /// </summary>
        public Template Template { get; }
        /// <summary>
        /// 模板实例
        /// </summary>
        public object Instance { get; }
        /// <summary>
        /// 输出文件路径
        /// </summary>
        public string SavePath { get; }

        public TimeSpan Elapsed { get; private set; } = TimeSpan.MaxValue;

        public Exception Exception { get; private set; } = null;

        public IAsyncResult AsyncResult { get; private set; } = null;

        /// <summary>
        /// 构造并开始异步任务
        /// </summary>
        /// <param name="template"></param>
        /// <param name="instance"></param>
        /// <param name="outputfile"></param>
        public ReplaceTask(Template template, object instance, string outputfile, bool multiThreadMode)
        {
            this.Template = template;
            this.Instance = instance;
            this.SavePath = outputfile;
            if (multiThreadMode)
            {
                var action = new Action(Execute);
                this.AsyncResult = action.BeginInvoke(null, null);
            }
            else
            {
                Execute();
                if (this.Exception != null) throw this.Exception;
            }
        }

        private void Execute()
        {
            var t = Stopwatch.StartNew();
            try
            {
                Template.ReplaceToFile(Instance, SavePath);
                t.Stop();
            }
            catch (Exception ex)
            {
                this.Exception = ex;
                t.Stop();
            }
        }
    }
}
